import echarts from 'echarts';
import "echarts-gl"
import {esri} from "../../../api/esriAPI";
import {jsUtils} from "../../../utils/jsUtils";


/**
 * Echarts图层
 * @class
 * */
export const EchartLayer = class {
  name = "EchartsglLayer";//名称
  view = null;//视图--2D/3D
  box = null;//用于存放echarts的DOM对象
  chart = null;//echart对象
  chartOption = null;//echart的option配置
  visible = true;//是否显示
  _curMapDOM = null;//当前的map的DOM容器
  _debounceTime = 200;//地图范围发生变化，延迟多久触发echarts更新
  /**
   * 构造函数
   * @param {String} mapId 地图的mapId
   * @param {Object} option echart的配置项
   * @param {Number} debounceTime 去抖动的时间
   */
  constructor(viewManage, option, debounceTime = 200) {
    this._debounceTime = debounceTime
    let view = viewManage.getView();
    this._curMapDOM = viewManage.getDOM();
    echarts.registerCoordinateSystem('arcgis', this.getE3CoordinateSystem(view));
    this.init(view, option);
  };

  /**
   * 初始化
   * @param  {Object} view arcgis的view对象
   * @param  {Object} option echart的配置项
   */
  init(view, option) {
    this.setBaseMap(view);
    this.createLayer();
    this.setChartOption(option);
  };

  /**
   * 存储view
   * @param  {Object} view arcgis的view对象
   */
  setBaseMap(view) {
    this.view = view;
  };

  /**
   * 存储echart的option,同时初始化echart
   * @param  {Object} option echart的配置项
   */
  setChartOption(option) {
    this.chartOption = option;
    this.setCharts();
  };

  /**
   * 是否显示
   * @param bool {Boolean} 是否显示
   */
  setVisible(bool) {
    if (!this.box || this.visible === bool) return;
    this.box.hidden = !bool;
    this.visible = bool;
    bool === true && setCharts();
  };

  /**
   * 刷新开始
   */
  refreshBegin() {
    this.box.hidden = true;
  };

  /**
   * 刷新中
   */
  refreshing() {
    setCharts();
  };

  /**
   * 刷新结束
   */
  refreshEnd() {
    this.box.hidden = false;
  };

  /**
   * 事件的监听
   * @param eventName 事件名称
   * @param handler 响应
   * @param context 上下文
   */
  on(eventName, handler, context) {
    this.chart.on(eventName, handler, context);
  };

  /**
   * 移除事件的监听
   * @param eventName 事件名称
   * @param handler 响应
   * @param context 上下文
   */
  off(eventName, handler, context) {
    this.chart.off(eventName, handler, context);
  };

  map_ExtentChange_Listener = null;

  /**
   * 设置echarts
   */
  setCharts() {
    if (!this.visible) return;
    if (this.chartOption == null || this.chartOption == 'undefined') return;
    let baseExtent = this.view.extent;
    //判断是否使用了mark类型标签，每次重绘要重新转换地理坐标到屏幕坐标
    //根据地图extent,重绘echarts
    this.chartOption.xAxis = {show: false, min: baseExtent.xmin, max: baseExtent.xmax};
    this.chartOption.yAxis = {show: false, min: baseExtent.ymin, max: baseExtent.ymax};
    this.chart.setOption(this.chartOption);
    this.chartOption.animation = false;
  };

  /**
   * 创建layer的容器，添加到map的layers下面
   */
  createLayer() {
    let box = this.box = document.createElement("div");
    box.setAttribute("id", "testData")
    box.setAttribute("name", "testData")
    box.style.width = this.view.width + 'px';
    box.style.height = this.view.height + 'px';
    box.style.position = "absolute";
    box.style.top = "0";
    box.style.left = "0";
    let parent = this._curMapDOM.getElementsByClassName("esri-view-surface")[0];
    parent.appendChild(box);
    this.chart = echarts.init(box);
    // this.chart.on("mousedown",function(params){
    //   console.log(params)
    //   var name=params.name;
    //   var value=params.value;
    //   console.info(name+"\n"+value);
    // })
    //this.setCharts();
    this.startMapEventListeners();
  };

  /**
   * 销毁实例
   */
  removeLayer() {
    this.box.outerHTML = "";
    this.view = null;
    this.box = null;
    this.originLyr = null;
    this.features = null;
    this.screenData = [];
    this.chartOption = null;
    this.map_ExtentChange_Listener.remove();
    this.chart.clear();
    this.chart = null;

  };

  /**
   * 监听地图事件，根据图层是否显示，判断是否重绘echarts
   */
  startMapEventListeners() {
    let view = this.view;
    this.map_ExtentChange_Listener = view.watch("extent", jsUtils.debounce(function () {
      if (!this.visible) return;
      this.setCharts();
      this.chart.resize();
      this.box.hidden = false;
    }.bind(this), this._debounceTime));
  };

  /**
   * 获得echart和地图的坐标转换关系
   * @param map 地图对象
   * @returns {CoordSystem} echart和地图的坐标转换关系
   */
  getE3CoordinateSystem(map) {
    var CoordSystem = function CoordSystem(map) {
      this.dataMap = {};
      this.map = map;
      this._spatialReference =map.spatialReference;
      this._mapOffset = [0, 0];
    };
    CoordSystem.create = function (ecModel) {
      ecModel.eachSeries(function (seriesModel) {
        if (seriesModel.get('coordinateSystem') === 'arcgis') {
          seriesModel.coordinateSystem = new CoordSystem(map);
        }
      });
    };
    CoordSystem.getDimensionsInfo = function () {
      return ['x', 'y'];
    };
    CoordSystem.dimensions = ['x', 'y'];
    CoordSystem.prototype.dimensions = ['x', 'y'];
    CoordSystem.prototype.setMapOffset = function setMapOffset(mapOffset) {
      this._mapOffset = mapOffset;
    }
    CoordSystem.prototype.dataToPoint = function dataToPoint(data) {
      let strKey = "" + data[0] + data[1]
      if (this.dataMap[strKey]) {
        return this.dataMap[strKey];
      }
      // var point = {
      //   type: "point",
      //   // x: data[0],
      //   // y: data[1],
      //   longitude: data[0],
      //   latitude: data[1],
      //   spatialReference: this._spatialReference
      // };
      let longitude = data[0];
      let latitude = data[1];
      let spatialReference = this._spatialReference;
      let point = new esri.Point({longitude, latitude, spatialReference});
      var px = map.toScreen(point);
      var mapOffset = this._mapOffset;
      let newP = [px.x - mapOffset[0], px.y - mapOffset[1]];
      this.dataMap[strKey] = newP;
      console.log("echart",data,px.x,px.y);
      return newP;
    }
    CoordSystem.prototype.pointToData = function pointToData(pt) {
      var mapOffset = this._mapOffset;
      var screentPoint = {
        x: pt[0] + mapOffset[0],
        y: pt[1] + mapOffset[1]
      };
      var data = map.toMap(screentPoint);
      return [data.x, data.y];
    };
    CoordSystem.prototype.getViewRect = function getViewRect() {
      return new graphic.BoundingRect(0, 0, this.map.width, this.map.height);
    };
    CoordSystem.prototype.getRoamTransform = function getRoamTransform() {
      return matrix.create();
    };
    return CoordSystem
  }

}
